package com.example.star.controller;

import com.example.star.entity.Star;
import com.example.star.entity.User;
import com.example.star.service.StarService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.security.Principal;
import java.util.List;

@Controller
public class StarController {

    @Autowired
    private StarService starService;

    @GetMapping("/stars")
    @ResponseBody
    public List<Star> getStars() {
        return starService.getAllStars();
    }

    @PostMapping("/stars")
    @ResponseBody
    public Star saveStar(@RequestBody Star star) {
        starService.saveStar(star);
        return star; // 返回保存的Star对象
    }
    @GetMapping("/star-list")
    public String showStarList(@RequestParam(defaultValue = "1") int page,
                               @RequestParam(defaultValue = "8") int size,
                               Model model) {
        List<Star> stars = starService.getStarsByPage(page, size);
        int totalStars = starService.getTotalStars();
        int totalPages = (int) Math.ceil((double) totalStars / size);

        model.addAttribute("stars", stars);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);

        return "star-list";
    }

    @PostMapping("/stars/{id}")
    public String deleteStar(@PathVariable int id, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        // 从 HttpSession 中获取用户信息
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            redirectAttributes.addFlashAttribute("error", "你还未登录，请先登录");
            return "redirect:/login"; // 重定向到登录页面
        }

        User user = (User) userObj;
        // 假设管理员角色名称为 "ADMIN"，根据实际情况修改
        if ("ADMIN".equals(user.getRole())) {
            try {
                starService.deleteStar(id);
                redirectAttributes.addFlashAttribute("message", "明星信息删除成功");
            } catch (Exception e) {
                redirectAttributes.addFlashAttribute("error", "删除明星信息时出现错误：" + e.getMessage());
            }
        } else {
            redirectAttributes.addFlashAttribute("error", "你没有权限删除明星信息");
        }
        return "redirect:/star-list";
    }
}